'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require('@yunke/art-dialog').default;
    require("../../../plugins/select2/select2");
    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('../contract-common');
    var myMath = require('../../common/my-math');

    var ContractReceivableFund = angular.module('ContractReceivableFund', ['ContractCommonService']);

    ContractReceivableFund.filter('signOrIncomeAmount', function () {
            return function (contract) {
                //云客签约-直属区域/云客签约-联营区域/云客直销
                //使用签约金额
                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
                if (contract.contract_property_id == limitContractArr[0] || contract.contract_property_id == limitContractArr[1] || contract.contract_property_id == limitContractArr[2]) {
                    return contract.sign_amount;
                } else {
                    return contract.income_amount ? contract.income_amount : 0;
                }
            }
        })
        .filter('sumIncomeAmount', function () {
            return function (receivables) {
                var amount = 0;
                if (receivables) {
                    $.each(receivables, function (i, d) {
                        if (d.__type == 'delete') {
                            return;
                        }
                        amount = myMath.add(amount, d.receivable_amount);
                    });
                }

                return amount;
            }

        })
        .filter('remainIncomeAmount2', function () {
            return function (receivables, contract) {
                var amount = 0;
                if (receivables) {
                    $.each(receivables, function (i, d) {
                        if (d['__type'] == 'delete') {
                            return;
                        }
                        amount = myMath.add(amount, parseFloat(d.receivable_amount));
                    });
                }


                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];

                if (contract.contract_property_id == limitContractArr[0] || contract.contract_property_id == limitContractArr[1]) {
                    return myMath.sub(contract.sign_amount, amount);
                } else {
                    return myMath.sub(contract.income_amount, amount);
                }

                return 0;
            }
        })
        .service('receivableFundService', ['$rootScope', 'contractCommonService', function ($rootScope, contractCommonService) {
            $rootScope.fundInfo = {};
            $rootScope.editFunds = [];
            var service = {
                onFundEditShow: function ($data, $dialog, $dialogScope, oldFund, isSplit, remainIncomeAmount) {
                    /**
                     * 打开款项编辑界面时初始化
                     * oldFund: 原款项/被拆分款项
                     * isSplit: 是否拆分（如果为true则oldFund为被拆分款项）
                     * remainIncomeAmount: 应收金额最大限制
                     */
                    /*先处理下拉框数据*/
                    //获取合同信息
                    //获取合同信息
                    contractCommonService.getContract($data, function (data) {
                        if (data) {
                            $dialogScope.contractBaseInfo = data.contract;
                            service.judgeInvoice = $dialogScope.contractBaseInfo.attribute_name;
                            $dialogScope.$applyAsync();
                        }

                    });

                    $dialogScope.maxIncomeAmount = remainIncomeAmount;

                    //应收款名称下拉框
                    $dialogScope.ddlConfigFundName = {
                        allowClear: false,
                        data: [],
                        placeholder: '应收款名称'
                    };

                    contractCommonService.getReceivableFundName(function (data) {
                        var ddlData = [];
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.receivable_item_id, text: d.receivable_item_name});
                        });
                        $dialogScope.ddlConfigFundName.data = ddlData;
                        $dialogScope.$applyAsync();
                    });

                    //款项小类下拉框
                    $dialogScope.ddlConfigFundSmallClass = {
                        allowClear: false,
                        data: [],
                        placeholder: '款项小类'
                    };
                    contractCommonService.getFundSmallClass($dialogScope.contractBaseInfo.contract_property_id, function (data) {
                        var ddlData = [];
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.money_category_item_id, text: d.money_category_item_name});
                        });
                        $dialogScope.ddlConfigFundSmallClass.data = ddlData;
                        $dialogScope.$applyAsync();
                    });

                    //收入类别
                    $dialogScope.ddlConfigIncomeCategory = {
                        allowClear: false,
                        data: [],
                        placeholder: '核算收入类别',
                        onchange2: function (newVal, scope) {
                            if (scope) {
                                scope.type_name = newVal.text;
                            }
                        }
                    };
                    //获取核算收入类别下拉信息
                    contractCommonService.getBussAccountTypes(function (data) {
                        var ddlData = [];
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.type_id, text: d.type_name});
                        });
                        $dialogScope.ddlConfigIncomeCategory.data = ddlData;
                        $dialogScope.$applyAsync();
                    });
                    //收款责任人下拉框
                    $dialogScope.ddlConfigDutyOfficer = {
                        ajax: {
                            url: api_prefix + "erp-interface/get-users",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            cache: true
                        },
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            $dialogScope.data.fundInfo.department_id = newVal.DepartmentId;
                            $dialogScope.data.fundInfo.department_name = newVal.DepartmentName;
                        }
                    };
                    //收款责任人默认值  合同类型为云客签约-直属区域时
                    if(oldFund==null && $dialogScope.contractBaseInfo.contract_property_id=="7f83719a-fce8-11e4-bed8-00155d02c832"){
                      setTimeout(function(){
                        $('#idFundInfoPayeeId').data('select2').updateSelection({id:$dialogScope.contractBaseInfo.sign_people_id,text:$dialogScope.contractBaseInfo.sign_people_name});
                        $dialogScope.data.fundInfo.payee_id = $dialogScope.contractBaseInfo.sign_people_id;
                      },0);
                      //获取用户信息 并设置
                      if($dialogScope.contractBaseInfo.sign_people_id!=""){
                        util.myAjax({
                            url: api_prefix + "erp-interface/get-user&userGUID="+$dialogScope.contractBaseInfo.sign_people_id,
                            type: "GET",
                            context: this,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    //收款责任人部门
                                    if(json.data!=null){
                                        $dialogScope.data.fundInfo.department_id = json.data.DepartmentId;
                                        $dialogScope.data.fundInfo.department_name=json.data.DepartmentName;
                                    }
                                } else {
                                    util.alert("获取责任人部门失败：" + json.errMsg);
                                }
                            }
                        });
                      }
                    }

                    //合同类型为联营签约-云客结算
                    if(oldFund==null && $dialogScope.contractBaseInfo.contract_property_id=="7f856e81-fce8-11e4-bed8-00155d02c832"){
                      var now = new Date(),
                          now_y = now.getFullYear(),
                          now_m = now.getMonth()+ 1,
                          now_M = (now_m > 9) ? now_m : ('0'+now_m),
                          now_d = now.getDate(),
                          now_D = (now_d > 9) ? now_d : ('0' + now_d),
                          format_now = now_y + '-' + now_M + '-'+ now_D;
                          //责任人 默认为付小玲
                          const fxlGUID="a3c8f32d-374b-4772-95e9-0f3a84f2f1a1";
                          setTimeout(function(){
                            //应收款名称
                            $('#idReceivableItemId').data('select2').updateSelection({id:"882-fd02-11e4-bed8-00155d02c832",text:"云客租用款"});
                            $dialogScope.data.fundInfo.receivable_item_id="882-fd02-11e4-bed8-00155d02c832";
                            //款项小类
                            $('#idMoneyCategoryItemId').data('select2').updateSelection({id:"4d17ed28-005a-11e5-bed8-00155d02c832",text:"联营区域收入"});
                            $dialogScope.data.fundInfo.money_category_item_id="4d17ed28-005a-11e5-bed8-00155d02c832";
                            //应收金额默认
                            $dialogScope.data.fundInfo.receivable_amount=$dialogScope.contractBaseInfo.income_amount;
                            //应收日期
                            $dialogScope.data.fundInfo.receivable_date=format_now;
                            //付款条件
                            $dialogScope.data.fundInfo.payment_condition="款到开通授权";

                            $('#idFundInfoPayeeId').data('select2').updateSelection({id:fxlGUID,text:"付小玲"});
                            $dialogScope.data.fundInfo.payee_id = fxlGUID;
                          },0);
                          util.myAjax({
                            url: api_prefix + "erp-interface/get-user&userGUID="+fxlGUID,
                            type: "GET",
                            context: this,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    //收款责任人部门
                                    if(json.data!=null){
                                        $dialogScope.data.fundInfo.department_id = json.data.DepartmentId;
                                        $dialogScope.data.fundInfo.department_name=json.data.DepartmentName;
                                    }
                                } else {
                                    util.alert("获取责任人部门失败：" + json.errMsg);
                                }
                            }
                        });
                    }

                    //联合置业顾问
                    $dialogScope.ddlConfigUniteSales = {
                        ajax: {
                            url: api_prefix + "erp-interface/get-users",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            cache: true
                        },
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            $dialogScope.data.fundInfo.unite_sales_id = newVal.id;
                            $dialogScope.data.fundInfo.unite_sales_name = newVal.text;
                        }
                    };


                    $dialogScope.orgianlFund = oldFund;
                    $dialogScope.isSplit = isSplit;
                    $dialogScope.data.fundInfo = angular.extend({}, oldFund, {contract_id: $data});
                    var arr = service.judgeInvoice.split(',');
                    if (!$dialogScope.data.fundInfo.receivable_type) {
                        $dialogScope.data.fundInfo.receivable_type = 1;
                        //arr[0]代表新签，arr[1]代表混签，arr[2]代表续签，只有单独续签是true时receivable_type=2，其余情况为1
                        if (arr[2] == 'true' && arr[0] != 'true' && arr[1] != 'true') {
                            $dialogScope.data.fundInfo.receivable_type = 2;
                        } else {
                            $dialogScope.data.fundInfo.receivable_type = 1;
                        }
                    }
                    if (isSplit && $dialogScope.data.fundInfo) {
                        $dialogScope.data.fundInfo.old_receivable_id = $dialogScope.data.fundInfo.receivable_id;
                        $dialogScope.data.fundInfo.receivable_id = null;//如果是拆分款项，则为新增模式
                    }
                    if (oldFund) {
                        setTimeout(function () {
                            //$('.idReceivableId:last').data('select2').updateSelection({text: oldFund.receivable_item_name || oldFund.receivable_item_id});
                            $('.idDutyOfficer:last').data('select2').updateSelection({text: oldFund.payee_name || oldFund.payee_id});
                            $('.idUniteSales:last').data('select2').updateSelection({text: oldFund.unite_sales_name || oldFund.unite_sales_id});
                        }, 0);


                    } else {
                        //获取收入
                        contractCommonService.getContractRevenue($data, function (data) {
                            if (data && data.revenueList && data.revenueList.length > 0) {
                                $dialogScope.data.fundInfo.revenue_type = data.revenueList[0].revenue_type;
                                $rootScope.$applyAsync();
                            }
                        });
                    }

                    contractCommonService.getContractReceivable($data, function (data) {
                        /**
                         * 获取款项列表
                         */
                        $dialogScope.editFunds = data;
                        $dialogScope.$applyAsync();
                    });

                },
                onFundEditChangePayeeShow: function ($data, $dialog, $dialogScope, oldFund) {
                    /**
                     * 打开款项变更责任人界面时初始化
                     * oldFund: 原款项
                     */
                    $dialogScope.data.fundInfo = angular.extend({}, oldFund, {contract_id: $data});
                    //收款责任人下拉框
                    $dialogScope.ddlConfigDutyOfficer = {
                        ajax: {
                            url: api_prefix + "erp-interface/get-users",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            cache: true
                        },
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            $dialogScope.data.fundInfo.department_id = newVal.DepartmentId;
                            $dialogScope.data.fundInfo.department_name = newVal.DepartmentName;
                        }
                    };
                    //联合置业顾问
                    $dialogScope.ddlConfigUniteSales = {
                        ajax: {
                            url: api_prefix + "erp-interface/get-users",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            cache: true
                        },
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            //$dialogScope.data.fundInfo.unite_sales_id = newVal.DepartmentId;
                        }
                    };

                },
                onFundEditChangeItemShow: function ($data, $dialog, $dialogScope, oldFund) {
                    $dialogScope.data.fundInfo = angular.extend({}, oldFund, {contract_id: $data});
                    $dialogScope.ddlConfigFundName = {
                        allowClear: false,
                        data: [],
                        placeholder: '应收款名称'
                    };

                    contractCommonService.getReceivableFundName(function (data) {
                        var ddlData = [];
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.receivable_item_id, text: d.receivable_item_name});
                        });
                        $dialogScope.ddlConfigFundName.data = ddlData;
                        $dialogScope.$applyAsync();
                    });
                },
                onFundEditChangeRevenueTypeShow: function ($data, $dialog, $dialogScope, oldFund) {
                    $dialogScope.data.fundInfo = angular.extend({}, oldFund, {contract_id: $data});
                    //收入类别
                    $dialogScope.ddlConfigIncomeCategory = {
                        allowClear: false,
                        data: [],
                        placeholder: '核算收入类别',
                        onchange2: function (newVal, scope) {
                            if (scope) {
                                scope.type_name = newVal.text;
                            }
                        }
                    };
                    //获取核算收入类别下拉信息
                    contractCommonService.getBussAccountTypes(function (data) {
                        var ddlData = [];
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.type_id, text: d.type_name});
                        });
                        $dialogScope.ddlConfigIncomeCategory.data = ddlData;
                        $dialogScope.$applyAsync();
                    });
                },
                editFundSave: function ($data, $dialog, $dialogScope, callback) {
                    /**
                     * 保存新增款项
                     */
                    var fundInfo = $dialogScope.data.fundInfo;
                    //校验
                    //如果是拆分模式，则应收金额必须小于被拆分款项
                    if ($dialogScope.isSplit && fundInfo.receivable_amount >= $dialogScope.orgianlFund.receivable_amount) {
                        util.alert('应收金额必须小于被拆分款项金额（' + $dialogScope.orgianlFund.receivable_amount + ')');
                        return false;
                    }


                    var post_data = fundInfo;
                    var url;
                    if ($dialogScope.isSplit) {
                        url = api_prefix + "/receivable/split-contract-receivalble";
                    } else {
                        url = api_prefix + "/receivable/save-contract-receivable";
                    }

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("保存成功");
                                if (callback) {
                                    callback();
                                }

                                $dialog.close();
                            } else {
                                util.alert("保存失败：" + json.errMsg);
                            }
                        }
                    });
                    return false;
                },
                changeRevenueType: function ($data, $dialog, $dialogScope, callback) {
                    /**
                     * 变更责任人
                     */
                    var fundInfo = $dialogScope.data.fundInfo;
                    //校验
                    if (fundInfo.revenue_type == fundInfo.revenue_type_new) {
                        util.alert('新关联收入项和原关联收入项相同');
                        return false;
                    }

                    fundInfo.revenue_type = fundInfo.revenue_type_new;

                    var post_data = fundInfo;
                    var url;
                    url = api_prefix + "/receivable/change-responsible-revenue-type";

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("关联收入项变更成功");
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert("关联收入项变更失败：" + json.errMsg);
                            }
                        }
                    });
                },
                changeItem: function ($data, $dialog, $dialogScope, callback) {
                    /**
                     * 变更责任人
                     */
                    var fundInfo = $dialogScope.data.fundInfo;
                    //校验
                    if (fundInfo.receivable_item_id == fundInfo.receivable_item_id_new) {
                        util.alert('新款项名称和原款项名称相同');
                        return false;
                    }

                    fundInfo.receivable_item_id = fundInfo.receivable_item_id_new;

                    var post_data = fundInfo;
                    var url;
                    url = api_prefix + "/receivable/change-responsible-item";

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("款项变更成功");
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert("款项变更失败：" + json.errMsg);
                            }
                        }
                    });
                },
                changePayee: function ($data, $dialog, $dialogScope, callback) {
                    /**
                     * 变更责任人
                     */
                    var fundInfo = $dialogScope.data.fundInfo;
                    //校验
                    if (fundInfo.payee_id == fundInfo.payee_id_new) {
                        util.alert('新责任人和原责任人相同');
                        return false;
                    }

                    fundInfo.payee_id = fundInfo.payee_id_new;

                    var post_data = fundInfo;
                    var url;
                    url = api_prefix + "/receivable/change-responsible-person";

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("责任人变更成功");
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert("责任人变更失败：" + json.errMsg);
                            }
                        }
                    });
                },
                changeReceivableDate: function ($data, $dialog, $dialogScope, callback) {
                    /**
                     * 变更应收日期
                     */
                    var fundInfo = $dialogScope.data.fundInfo;
                    //校验
                    if (fundInfo.receivable_date == $data.receivable_date_new) {
                        util.alert('新应收日期和原应收日期相同');
                        return false;
                    }
                    fundInfo.receivable_date = fundInfo.receivable_date_new;

                    var post_data = fundInfo;
                    var url;
                    url = api_prefix + "/receivable/change-receivable-date";

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("应收日期变更成功");
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert("应收日期变更失败：" + json.errMsg);
                            }
                        }
                    });
                },
                deleteFund: function (fundInfo) {
                    /**
                     * 删除款项
                     */
                    util.confirm('确定要删除此款项吗?', {
                        ok: function () {
                            var post_data = {receivable_id: fundInfo.receivable_id};
                            var url;
                            url = api_prefix + "/receivable/delete-contract-receivable";

                            util.myAjax({
                                url: url,
                                type: "POST",
                                context: this,
                                data: post_data,
                                success: function (json) {
                                    if (json.retCode == 0) {
                                        fundInfo.__isdelete = 1;
                                        util.alert("删除成功");
                                        $rootScope.$applyAsync();
                                    } else {
                                        util.alert("删除失败：" + json.errMsg);
                                    }
                                }
                            });
                        }
                    });
                },
                markOperation: function (fundInfo, isOperation, callback) {
                    /**
                     * 设置运营关注款
                     */
                    var post_data = {receivable_id: fundInfo.receivable_id, is_operation: isOperation};
                    var url;
                    url = api_prefix + "/receivable/mark-operation";

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                if (callback) {
                                    callback();
                                }
                                util.alert(isOperation ? "设置运营关注款成功" : "取消运营关注款成功");
                            } else {
                                util.alert((isOperation ? "设置运营关注款失败：" : "取消运营关注款失败：") + json.errMsg);
                            }
                        }
                    });
                },
                markBadBebt: function (fundInfo, isBad, callback) {
                    /**
                     * 标记坏账
                     */
                    var post_data = {receivable_id: fundInfo.receivable_id, is_bad_debt: isBad};
                    var url;
                    url = api_prefix + "/receivable/mark-bad-debt";

                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        success: function (json) {
                            if (json.retCode == 0) {
                                if (callback) {
                                    callback();
                                }
                                util.alert(isBad ? "标记为坏账成功" : "取消标记坏账成功");
                            } else {
                                util.alert((isBad ? "标记为坏账失败：" : "取消标记坏账失败：") + json.errMsg);
                            }
                        }
                    });
                },
                markBadBebtConfim: function (fundInfo, isBad, callback) {
                    var that = this;
                    util.confirm(isBad ? '是否标记为坏账' : '是否取消标记坏账', {
                        ok: function () {
                            that.markBadBebt(fundInfo, isBad, callback);
                        }
                    });
                }
            };
            return service;
        }]);

    module.exports = ContractReceivableFund;
});
